package com.tencent.wxcloudrun.controller;

import com.tencent.wxcloudrun.config.ApiResponse;
import com.tencent.wxcloudrun.dto.HxUserRequest;
import com.tencent.wxcloudrun.model.HxUser;
import com.tencent.wxcloudrun.service.HxUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
public class HxUserController {
    final HxUserService hxUserService;
    final Logger logger;

    public HxUserController(HxUserService hxUserService) {
        this.hxUserService = hxUserService;
        this.logger = LoggerFactory.getLogger(HxUserController.class);
    }

    @GetMapping("/MP_verify_YgV355O8RkWmJbAG.txt")
    public String verify(){
        return "YgV355O8RkWmJbAG";
    }

    @GetMapping(value = "/api/hxUser")
    ApiResponse get(@RequestHeader(value = "X-WX-OPENID") String uid) {
        logger.info("/api/hxUser get request");
        Optional<HxUser> hxUser = hxUserService.getUser(uid);

        return ApiResponse.ok(hxUser);
    }

    @PostMapping(value = "/api/hxUser")
    ApiResponse create(@RequestHeader(value = "X-WX-OPENID") String uid) {
        logger.info("/api/hxUser post request");
        Optional<HxUser> user = hxUserService.getUser(uid);
        if (user.isPresent()) {
            if(user.get().getId() != null){
                return ApiResponse.ok(user.get());
            }
        }

        HxUser user1 = new HxUser();
        user1.setUid(uid);

        hxUserService.addUser(user1);
        return ApiResponse.ok(user1);
    }

    @GetMapping(value = "/api/hxUser/collect")
    ApiResponse collect(@RequestParam(name="id")Integer id) {
        logger.info("/api/hxUser/collect get request");

        //领取礼物的动作
        hxUserService.collectGift(id);


        Optional<HxUser> hxUser = hxUserService.getUserById(id);
        return hxUser.map(ApiResponse::ok).orElseGet(() -> ApiResponse.error("领取失败，请重新领取"));
    }
}
